var Browser = new Object();

Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != - 1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != - 1);

function confirmurl(url,message) {
	if(confirm(message)) redirect(url);
}
function redirect(url) {
	location.href = url;
}


function rowindex(tr)
{
  if (Browser.isIE)
  {
    return tr.rowIndex;
  }
  else
  {
    table = tr.parentNode.parentNode;
    for (i = 0; i < table.rows.length; i ++ )
    {
      if (table.rows[i] == tr)
      {
        return i;
      }
    }
  }
}

/**
 * 全选checkbox,注意：标识checkbox id固定为为check_box
 * @param string name 列表check名称,如 uid[]
 */
function selectall(name) {
	if ($("#check_box").attr("checked")==true) {
		$("input[name='"+name+"']").each(function() {
  			$(this).attr("checked","checked");
			
		});
	} else {
		$("input[name='"+name+"']").each(function() {
  			$(this).removeAttr("checked");
		});
	}
}
function openwinx(url,name,w,h) {
	if(!w) w=screen.width-4;
	if(!h) h=screen.height-95;
    window.open(url,name,"top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
}
//弹出对话框
function omnipotent(id,linkurl,title,close_type,w,h) {
	if(!w) w=700;
	if(!h) h=500;
	art.dialog({id:id,iframe:linkurl, title:title, width:w, height:h, lock:true},
	function(){
		if(close_type==1) {
			art.dialog({id:id}).close()
		} else {
			var d = art.dialog({id:id}).data.iframe;
			var form = d.document.getElementById('dosubmit');form.click();
		}
		return false;
	},
	function(){
			art.dialog({id:id}).close()
	});void(0);
}
//TAB切换
function SwapTab(name,cls_show,cls_hide,cnt,cur){
	for(i=1;i<=cnt;i++){
		if(i==cur){
			 $('#div_'+name+'_'+i).show();
			 $('#tab_'+name+'_'+i).attr('class',cls_show);
		}else{
			 $('#div_'+name+'_'+i).hide();
			 $('#tab_'+name+'_'+i).attr('class',cls_hide);
		}
	}
}
function LanguageTab(name,cls_show,cls_hide,cnt,cur){
	for(i=1;i<=cnt;i++){
		if(i==cur){
			 $('#div_lang_'+name+'_'+i).show();
			 $('#lang_'+name+'_'+i).attr('class',cls_show);
		}else{
			 $('#div_lang_'+name+'_'+i).hide();
			 $('#lang_'+name+'_'+i).attr('class',cls_hide);
		}
	}
}
//图片预览
function showImage(filepath) {
	window.top.art.dialog({title:'预览',fixed:true, content:'<img src="'+filepath+'" onload="$(this).LoadImage(true, 500, 500,\'/statics/images/nopic.gif\');"/>'});	
}
$(function(){
	//xheditor编辑器上传图片
	if ($.xheditor) {
	  $('textarea.editor').xheditor({forcePtag:false, width:'80%',height:'200px',html5Upload:false,upImgUrl:"gpadmin.php?m=site&a=public_editor_upload"});
	}
});


function url(path) {
  var len = path.length;
  if (path !== '' && path.substr(len - 5) != '.html' && path.substr(len - 1) != '/') {
    path += '/';
  }
  return basePath + path;
}

function JsonToStr(o) {
  var arr = [];
  var fmt = function(s) {
  if (typeof s == 'object' && s != null) return JsonToStr(s);
  return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
  }
  for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
  return '{' + arr.join(',') + '}';
}
var JSON = {
		  encode : function(input) {
		  	if (!input)
		    return 'null'
		  	switch (input.constructor) {
		  	case String:
		    return '"' + input + '"'
		  	case Number:
		    return input.toString()
		  	case Boolean:
		    return input.toString()
		  	case Array:
		    var buf = []
		    for (i in input)
		    	buf.push(JSON.encode(input[i]))
		    return '[' + buf.join(', ') + ']'
		  	case Object:
		    var buf = []
		    for (k in input)
		    	buf.push(k + ' : ' + JSON.encode(input[k]))
		    return '{ ' + buf.join(', ') + '} '
		  	default:
		    return 'null'
		  	}
		  }
		}
function LTrim(str)
{
    var i;
    for(i=0;i<str.length;i++)
    {
        if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
    }
    str=str.substring(i,str.length);
    return str;
}

function RTrim(str)
{
    var i;
    for(i=str.length-1;i>=0;i--)
    {
        if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
    }
    str=str.substring(0,i+1);
    return str;
}

function Trim(str)
{
    return LTrim(RTrim(str));
}

var BOLING = {};
BOLING.productrelated = {
  pids : {},  
  len : 0,
  pid : null,
  initialize : function (el) {
   
  },
  relatedinit : function (el) {
    $('.isbothway').live('click', function(){
      var pid = $(this).attr("title");
      var status = $(this).val();
      var pids_string = $('#related_info').val();
      var pids = eval('(' + pids_string + ')');
      pids[pid]['isbothway'] = status;
      var new_string = JsonToStr(pids);
      $('#related_info').val(new_string);
    });
    $('.related_cancel').live("click",function(){
      var pid = $(this).attr("rel");
      BOLING.productrelated.del_row(this, pid);
    });
  },
  relatedaddlistinit : function (el) {
    $('#prosceniumaddrelated').click(function(){
      var self = BOLING.productrelated;
      var pids_string = $(window.parent.document).find('#related_info').val();
      var pids = eval('(' + pids_string + ')');
      var pids_add = {};
      var status = 0;
      $("[name='checkItem']:checked").each(function(){
          status = 0;
          var pid = $(this).val();
          for( var i in pids){
            if(pid == i){
              status = 1;
            }
          }
          pids[pid] = new Array(); 
          pids[pid]['pid'] = $(this).val();
          pids[pid]['name'] = $(this).attr("title");
          pids[pid]['isbothway'] = 1;
         if (status == 0) {
            pids_add[pid] = new Array(); 
            pids_add[pid]['pid'] = $(this).val();
            pids_add[pid]['name'] = $(this).attr("title");
            pids_add[pid]['isbothway'] = 1;
          }
      });
      if ($(window.parent.document).find('#IsInTagsInfoEdit').val() == 'YES') {
        var new_string = JSON.encode(pids);
      } else {
      	var new_string = JsonToStr(pids);
      }
      $(window.parent.document).find('#related_info').val(new_string);
      self.getviewaction(pids_add);
   });
  },
  getviewaction : function (pids){
    var self = BOLING.productrelated;
    $(window.parent.document).find("#add").hide();
    $(window.parent.document).find("#list").show();
    var listDataObject = parent.document.getElementById('datalist');
    $('datalist').find('tr').hide();
    self.add_row(listDataObject, pids);
    $('#related_info').val(String(pids));
  },
  add_row : function (obj, pids){
    var self = BOLING.productrelated;
    var isbothway = $(window.parent.document).find("#isbothway").val();
    for(var i in pids){
      if (self.len == 0) {
        var len = $(window.parent.document).find("#datalist").find("tr").prevAll().length + 1; 
      } else {
        var len = self.len + 1; 
      }
      self.len = len;
      var tr = obj.insertRow(1);
      var td;
      td = tr.insertCell(0);   
      td.innerHTML = '<a href="javascript:;" id="a_cancel_'+pids[i]['pid']+'" class="related_cancel" rel="'+pids[i]['pid']+'" >&nbsp;&nbsp;&nbsp;&nbsp;</a>';
      td = tr.insertCell(1);  
      td.innerHTML = pids[i]['name']
      if(isbothway != 'no') {
        td = tr.insertCell(2);  
        td.innerHTML = '<input class="isbothway" id="el-c9631-e855c" type="radio" name="isall_'+pids[i]['pid']+'" title="'+pids[i]['pid']+'" value="0" /> 单向关联&nbsp;<input class="isbothway" id="el-c9631-e855b" title="'+pids[i]['pid']+'" type="radio" name="isall_'+pids[i]['pid']+'" value="1" checked/> 双向关联';
      }
    }
  },   
  del_row : function (obj, pid){
    BOLING.productrelated.len--; 
    $(obj).closest('tr').remove();
    BOLING.productrelated.del_pids(pid);
  },
  del_pids : function (pid){
    var self = BOLING.productrelated;
    var pids_string = $('#related_info').val();
    var pids = eval('(' + pids_string + ')');
    var new_pids = {};
    for(var i in pids){
      if(i != pid){
        new_pids[i] = {};
        new_pids[i]['pid'] = pids[i]['pid'];    
        new_pids[i]['name'] = pids[i]['name'];
        new_pids[i]['isbothway'] = pids[i]['isbothway'];
      }
    }
    var new_string = JsonToStr(new_pids);
    $('#related_info').val(new_string);
  },
  puttoinput : function (pids) {
    var self = BOLING.productrelated;
    var str = "";
    for(var i in pids){
      if (str != "") {
        str += ",";
      }
      str += pids[i]['pid'];
    }
    return str;
  },
   checkboxButton : function(el) {
    el.click(function(e) {
      if ($('#checkAll').attr('checked')) {
        $('input.checkItem').attr('checked', true);
        $('#check_top_title').show();
      } else {
        $('input.checkItem').attr('checked', false);
      }
    });
  },
};
$(function(){
var doWhileExist = function(sModuleId, oFunction) {
    var el = $(sModuleId);
    if (el.length) oFunction(el);
  };
  doWhileExist('input#checkAll', BOLING.productrelated.checkboxButton);
  doWhileExist('div#productrelated', BOLING.productrelated.initialize);
  doWhileExist('div#related', BOLING.productrelated.relatedinit);
  doWhileExist('div#relatedaddlist', BOLING.productrelated.relatedaddlistinit);
});
